using UnityEngine;
using System.Collections;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Threading.Tasks;
using UnityEngine.Networking;
using UnityEngine.UI;
using System.Collections.Generic;
using Unity.VisualScripting;

public class DeepBricksChat : MonoBehaviour
{
    public InputField input;
    private JObject thread;
    private JObject run;
    private JObject answer;

    private string api_key = "Bearer sk-LN9C3mX0ePGVRFWZz0NYnsG7spiJhRaXp7RnTyzUAmLrB3M2";
    private string url = "https://api.deepbricks.ai/api/v1/threads";
    private void Start()
    {
         StartCoroutine(GetRequest(url, api_key, ""));
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Return))
        {
            if (input.text == "")
            {
                Debug.Log("输入为空，请重新输入");
            }
            else
            {
                string url1 = $"https://api.deepbricks.ai/api/v1/threads/{thread["id"]}/messages";
                MessageBody body = new MessageBody
                {
                    role = "user",
                    content = input.text
                };

                string jsonMessage = JsonUtility.ToJson(body);
                StartCoroutine(GetRequest_message(url1, api_key, jsonMessage));

                string url2 = $"https://api.deepbricks.ai/api/v1/threads/{thread["id"]}/runs";
                RunBody runBody = new RunBody
                {
                    model = "gpt-4o-mini"
                };
                string jsonRun = JsonUtility.ToJson(runBody);
                StartCoroutine(GetRequest_run(url2, api_key, jsonRun));


                string url3 = $"https://api.deepbricks.ai/api/v1/threads/{thread["id"]}/messages?run_id={run["id"]}";
                Debug.Log(url3);
                StartCoroutine(GetRequest_Get(url3, api_key));
                Debug.Log(answer);
            }



        }

    }







    IEnumerator GetRequest(string myurl, string myapi_key, string bodyDate)
        {
            string url = myurl;
            string bearerToken = myapi_key;
            string jsonData = bodyDate; // 假设你要发送的JSON数据  
            UnityWebRequest request = new UnityWebRequest(url, "POST");
            byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonData);
            request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
            request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();

            // 设置请求头  
            request.SetRequestHeader("Content-Type", "application/json");
            request.SetRequestHeader("Authorization", bearerToken);

            // 发送请求并等待响应  
            yield return request.SendWebRequest();

            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.Log(request.error);
            }
            else
            {
                thread = JObject.Parse(request.downloadHandler.text);
                Debug.Log(thread);
            }
        }

    IEnumerator GetRequest_message(string myurl, string myapi_key, string bodyDate)
    {
        string url = myurl;
        string bearerToken = myapi_key;
        string jsonData = bodyDate; // 假设你要发送的JSON数据  
        UnityWebRequest request = new UnityWebRequest(url, "POST");
        byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonData);
        request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
        request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();

        // 设置请求头  
        request.SetRequestHeader("Content-Type", "application/json");
        request.SetRequestHeader("Authorization", bearerToken);

        // 发送请求并等待响应  
        yield return request.SendWebRequest();

        if (request.result != UnityWebRequest.Result.Success)
        {
            Debug.Log(request.error);
        }

    }

    IEnumerator GetRequest_run(string myurl, string myapi_key, string bodyDate)
        {
            string url = myurl;
            string bearerToken = myapi_key;
            string jsonData = bodyDate; // 假设你要发送的JSON数据  
            UnityWebRequest request = new UnityWebRequest(url, "POST");
            byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonData);
            request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
            request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();

            // 设置请求头  
            request.SetRequestHeader("Content-Type", "application/json");
            request.SetRequestHeader("Authorization", bearerToken);

            // 发送请求并等待响应  
            yield return request.SendWebRequest();

            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.Log(request.error);
            }
            else
            {
                run = JObject.Parse(request.downloadHandler.text);
                Debug.Log(run);
            }
        }


        IEnumerator GetRequest_Get(string myurl, string myapi_key)
        {
            using (UnityWebRequest request = UnityWebRequest.Get(myurl))
            {
                // 设置请求头  
                request.SetRequestHeader("Authorization", myapi_key);

                // 发送请求并等待响应  
                yield return request.SendWebRequest();

                if (request.result != UnityWebRequest.Result.Success)
                {
                    Debug.LogError("Error: " + request.error);
                }
                else
                {
                    // 处理响应文本（例如，解析JSON）  
                    Debug.Log("Response: " + request.downloadHandler.text);
                    answer = JObject.Parse(request.downloadHandler.text);


                }
            }
        }
    }
